package org.ourgrid.broker.commands.executors;

import org.ourgrid.broker.BrokerConstants;
import org.ourgrid.broker.commands.SchedulerData;
import org.ourgrid.broker.controller.LocalWorkerProviderClientController;
import org.ourgrid.broker.dao.WorkerDAO;
import org.ourgrid.common.interfaces.Worker;
import org.ourgrid.common.interfaces.WorkerClient;
import org.ourgrid.common.interfaces.to.GridProcessHandle;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;

public class StartWorkExecutor extends SchedulerCommandExecutor {
	
	private String workerID;
	private long requestID;
	private int jobID;
	private int taskID;
	private int processID;

	
	/**
	 * <START_WORK workerID='String' requestID='long' jobID='int' taskID='int' processID='int'/> 
	 */
	public void execute(SchedulerData data, ServiceManager manager) {
		
		fillData(data.getXml());
		
		DeploymentID workerDeploymentID = new DeploymentID(workerID);
		
		Worker worker = manager.getDAO(WorkerDAO.class).getWorker(workerDeploymentID);
		
		worker.startWork(getWorkerClient(manager), requestID, new GridProcessHandle(jobID, taskID, processID));
		
	}
	
	private WorkerClient getWorkerClient(ServiceManager manager) {
		WorkerClient workerClient = 
			(WorkerClient) manager.getObjectDeployment(BrokerConstants.WORKER_CLIENT).getObject();
		
		if (workerClient == null) {
			manager.deploy(BrokerConstants.WORKER_CLIENT, LocalWorkerProviderClientController.class);
			workerClient = (WorkerClient) manager.getObjectDeployment(BrokerConstants.WORKER_CLIENT).getObject();
		}
		
		return (WorkerClient) workerClient;
	}
	
	private void fillData(String xml) {
		
		Document logDocFile = super.getXMl(xml);
		
		Element element = logDocFile.getDocumentElement();
		
		requestID = Long.valueOf(element.getAttribute("requestID"));
		workerID = element.getAttribute("workerID");
		jobID = Integer.valueOf(element.getAttribute("jobID"));
		taskID = Integer.valueOf(element.getAttribute("taskID"));
		processID = Integer.valueOf(element.getAttribute("processID"));
	}
}
